<template>
  <div>
    <van-nav-bar class="page-nav-bar" title="个人中心" left-arrow @click-left="$router.go(-1)"></van-nav-bar>
    <input type="file" hidden ref="inputFile" @change="inputChange">
    <van-cell title="头像" is-link @click="$refs.inputFile.click()">
      <van-image
        round
        class="avatar"
        :src="userData.photo"
      />
    </van-cell>
    <van-cell @click="showEditName = true" title="昵称" is-link :value="userData.name" />
    <van-cell @click="showEditGender = true" title="性别" is-link :value="userData.gender ? '女' : '男'" />
    <van-cell @click="showEditBirthday = true" title="生日" is-link :value="userData.birthday" />
    <!-- 编辑用户昵称 -->
    <van-popup v-model="showEditName" position="bottom" :style="{ height: '100%' }">
      <edit-name v-if="showEditName" v-model="userData.name" @closeEdit="showEditName = false"></edit-name>
    </van-popup>
    <!-- 编辑用户性别 -->
    <van-popup v-model="showEditGender" position="bottom">
      <edit-gender v-if="showEditGender" v-model="userData.gender" @closeEdit="showEditGender = false"></edit-gender>
    </van-popup>
    <!-- 编辑用户生日 -->
    <van-popup v-model="showEditBirthday" position="bottom">
      <edit-birthday v-if="showEditBirthday" v-model="userData.birthday" @closeEdit="showEditBirthday = false"></edit-birthday>
    </van-popup>
    <!-- 编辑头像 -->
    <van-popup v-model="showEditAvatar" position="bottom" :style="{ height: '100%' }">
      <edit-avatar v-if="showEditAvatar" @updataAvatar="userData.photo = $event" @close="showEditAvatar = false" :imgUrl="avatarUrl"></edit-avatar>
    </van-popup>
  </div>
</template>

<script>
import { getUserData } from '@/api/user'
import EditName from './components/edit-name'
import EditGender from './components/edit-gender'
import EditBirthday from './components/edit-birthday'
import EditAvatar from './components/edit-avatar'

export default {
  name: 'user',
  data () {
    return {
      userData: {},
      showEditName: false,
      showEditGender: false,
      showEditBirthday: false,
      showEditAvatar: false,
      avatarUrl: ''
    }
  },

  components: {
    EditName,
    EditGender,
    EditBirthday,
    EditAvatar
  },

  created () {
    this.getUserInfo()
  },

  methods: {
    async getUserInfo () {
      try {
        const { data: res } = await getUserData()
        this.userData = res.data
        console.log(res)
      } catch (err) {
        this.$toast('获取用户资料失败')
      }
    },
    inputChange () {
      const file = this.$refs.inputFile.files[0]
      // const blobUrl = URL.createObjectURL(file)
      this.showEditAvatar = true
      this.avatarUrl = URL.createObjectURL(file)
      this.$refs.inputFile.value = ''
    }
  }
}
</script>

<style scoped lang='less'>
.avatar {
  width: 50px;
  height: 50px;
}
</style>
